<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <a-form size="small" :model="pageData" layout="inline">
          <a-form-item label="设备编号">
            <a-input
              allow-clear
              :style="{ width: '200px' }"
              class="bacClass"
              placeholder=""
              v-model="dropDownData"
            />
          </a-form-item>
          <a-form-item label="设备名称">
            <a-input
              allow-clear
              :style="{ width: '200px' }"
              class="bacClass"
              placeholder=""
              v-model="dropDownData1"
            />
          </a-form-item>
          <a-form-item label="设备保养模板">
            <a-input
              allow-clear
              :style="{ width: '200px' }"
              class="bacClass"
              placeholder=""
              v-model="dropDownData2"
            />
          </a-form-item>
        </a-form>
        <div>
          <Toolbar
            :items="idTypes == 1 ? ['查询', '派工', '完成'] : idTypes == 2 ? ['查询'] : ['查询']"
            @select="selectHandler"
            @dispatch="dispatchs"
            @complete="completes"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-tabs
        :lazy-load="true"
        :justify="true"
        :default-active-key="2"
        @change="aTabsChanges"
        style="height: 100%"
      >
        <!-- <a-tab-pane :key="1" title="未派工">
                    <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                        rowSelection="multiple" @grid-ready="gridReady3" style="height:100%" :defaultColDef="defaultColDef"
                        class='ag-theme-alpine' :rowData="tableDataList3" :columnDefs="tc" :localeText="localeText1">
                    </AgGridVuesCopys>
                </a-tab-pane> -->
        <a-tab-pane :key="2" title="待处理">
          <AgGridVuesCopys
            :rowHeight="33"
            :headerHeight="33"
            :suppressCopyRowsToClipboard="true"
            rowSelection="multiple"
            @grid-ready="gridReady"
            style="height: calc(100% - 45px)"
            :defaultColDef="defaultColDef"
            class="ag-theme-alpine"
            :rowData="tableDataList"
            :columnDefs="tc"
            :localeText="localeText1"
          >
          </AgGridVuesCopys>
          <paginationCopys
            :total="fySelet.total"
            show-total
            show-jumper
            show-page-size
            @change="PageSize"
            @page-size-change="change"
            style="justify-content: center"
            :page-size="fySelet.size"
            :current="fySelet.page"
          />
        </a-tab-pane>
        <a-tab-pane :key="3" title="已处理">
          <AgGridVuesCopys
            :rowHeight="33"
            :headerHeight="33"
            :suppressCopyRowsToClipboard="true"
            rowSelection="multiple"
            @grid-ready="gridReady2"
            style="height: calc(100% - 45px)"
            :defaultColDef="defaultColDef"
            class="ag-theme-alpine"
            :rowData="tableDataList2"
            :columnDefs="tc"
            :localeText="localeText1"
          >
          </AgGridVuesCopys>
          <paginationCopys
            :total="fySelet.total"
            show-total
            show-jumper
            show-page-size
            @change="PageSize"
            @page-size-change="change"
            style="justify-content: center"
            :page-size="fySelet.size"
            :current="fySelet.page"
          />
        </a-tab-pane>
      </a-tabs>
    </template>
    <a-modal
      :width="500"
      v-model:visible="visible"
      :on-before-ok="handleOk"
      @cancel="() => (visible = false)"
      :mask-closable="false"
    >
      <template #title> 派工 </template>
      <a-form ref="formRef" :model="dataForm">
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item
              label="员工姓名"
              field="staff"
              label-col-flex="80px"
              :rules="[{ required: true, message: '员工姓名必填' }]"
              :validate-trigger="['change', 'blur']"
            >
              <a-select
                popup-container="html"
                class="bacClass"
                :default-value="dataForm.staff"
                :style="{ width: '250px' }"
                multiple
                v-model="dataForm.staff"
                allow-clear
                allow-search
              >
                <a-option v-for="item in wxYgList" :value="item.name">{{ item.name }} </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item
              label="日期"
              field="startMaintainTime"
              label-col-flex="80px"
              :rules="[{ required: true, message: '日期必填' }]"
              :validate-trigger="['change', 'blur']"
            >
              <a-date-picker
                popup-container="html"
                class="bacClass"
                v-model="dataForm.startMaintainTime"
                style="width: 250px"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
    <el-dialog
      title="详情"
      v-model="isShowDetailDialog"
      @close="isShowDetailDialog = false"
      :close-on-click-modal="false"
      top="30vh"
      width="700"
      center
    >
      <!-- <div class="detail-container">
        <div class="tag-row" v-for="(tag, index) in tagList" :key="index">
          <el-tag>{{ tag }}</el-tag>
        </div>
      </div> -->
      <div class="w-full" style="height: 300px; overflow: auto">
        <encapsulation-agrid ref="table1Ref" :configaggrid="configaggrid"></encapsulation-agrid>
      </div>
    </el-dialog>
  </pageTabelLayout>
</template>
<script setup lang="ts">
  import { post, get } from '@/api/http'
  import { ref, reactive, onMounted, toRefs, onUnmounted } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  
  import { Message, Modal } from '@arco-design/web-vue'
  import { localeText } from '@/api/aggridZw'
  import ButtionRender1 from '@/components/aggridCellRenDerer/buttionRender1.vue'
  import emitter from '@/hooks/useEventBus'
  const formRef = ref()
  const isShowDetailDialog = ref(false)
  const table1Ref = ref<any>(null)
  const editHandler = async (data: any) => {
    const params = {}
    try {
      console.log('data', data)
      const { machineCode, maintainName, id } = data
      if (idTypes.value == 2) {
        params['machineCode'] = machineCode
        params['keepTemplateName'] = maintainName
      } else if (idTypes.value == 3) {
        params['infoId'] = id
      }
      const res = await post({
        url:
          idTypes.value == 2
            ? 'zcTemRepair/upkeepTemplateDetailed/findDetailByTemplateNameAndMachineCode'
            : 'zcTemRepair/maintainDocument/selectInfoById',
        data: params,
      })
      if (res.code == 200) {
        isShowDetailDialog.value = true
        if (idTypes.value == 2) {
          nextTick(() => {
            table1Ref?.value.setdataListIterface(res.data)
            table1Ref.value.autoSizeAll()
          })
        } else if (idTypes.value == 3) {
          nextTick(() => {
            table1Ref?.value.setdataListIterface(res.data.info)
            table1Ref.value.autoSizeAll()
          })
        }
      } else {
        Message.error(res.message)
      }
    } catch (e) {
      console.log(e)
    }
  }
  onMounted(() => {
    emitter.on('MaintenanceForm-detailHandle', (data: any) => editHandler(data))
  })
  onUnmounted(() => {
    emitter.off('MaintenanceForm-detailHandle', (data: any) => editHandler(data))
  })
  const headerShow = ref(true)
  const localeText1: any = ref(localeText)
  const pageData: any = reactive({
    dropDownData: '',
    dropDownData1: '',
    dropDownData2: '',
    showAdd: false,
    sideTitle: '',
  })

  const { dropDownData, dropDownData1, dropDownData2, showAdd, sideTitle } = toRefs(pageData)

  const fySelet: any = reactive({
    total: 10,
    size: 10,
    page: 1,
  })

  const idTypes = ref(2)

  const aTabsChanges = (e: any) => {
    idTypes.value = e
    fySelet.size = 10
    fySelet.page = 1
    fySelet.total = 0
  }

  const PageSize = (val: any) => {
    fySelet.page = val
    if (idTypes.value == 1) {
      selectList()
    } else if (idTypes.value == 2) {
      selectList1()
    } else if (idTypes.value == 3) {
      selectList2()
    }
  }

  const change = (val: any) => {
    fySelet.size = val
    if (idTypes.value == 1) {
      selectList()
    } else if (idTypes.value == 2) {
      selectList1()
    } else if (idTypes.value == 3) {
      selectList2()
    }
  }

  const tableDataList: any = ref([])
  const gridOption = ref()
  const gridReady = (params: any) => {
    gridOption.value = params.api
  }

  const tableDataList2: any = ref([])
  const gridOption2 = ref()
  const gridReady2 = (params: any) => {
    gridOption2.value = params.api
  }

  const tableDataList3: any = ref([])
  const gridOption3 = ref()
  const gridReady3 = (params: any) => {
    gridOption3.value = params.api
  }
  const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
    flex: 1,
  }

  const tc = [
    {
      showRowGroup: 'hide_def',
      headerName: '',
      checkboxSelection: true,
      headerCheckboxSelection: true,
      pinned: 'left',
      width: 50,
      resizable: false,
      filter: false,
      sortable: false,
      minWidth: 50,
      maxWidth: 50,
      lockPosition: 'left',
    },
    {
      headerName: '序号',
      field: 'id',
      width: 150,
    },
    {
      headerName: '公司',
      field: 'companyName',
      width: 150,
    },
    {
      headerName: '保养模板',
      field: 'maintainName',
      width: 150,
    },
    {
      headerName: '本次日期',
      field: 'timeType',
      width: 150,
    },
    {
      headerName: '设备编号',
      field: 'machineCode',
      width: 150,
    },
    {
      headerName: '设备类型',
      field: 'machineType',
      width: 150,
    },
    {
      headerName: '设备名称',
      field: 'machine',
      width: 150,
    },
    {
      headerName: '保养员工',
      field: 'staff',
      width: 150,
    },
    {
      headerName: '操作',
      field: 'action',
      width: 150,
      pinned: 'right',
      cellRenderer: ButtionRender1,
      cellRendererParams: {
        buttonList: [
          {
            type: 'primary',
            text: '详情',
            typeName: 'el-button',
            show: true,
            Callback: (data: any) => {
              return {
                rowData: data,
                emitString: 'MaintenanceForm-detailHandle',
              }
            },
          },
        ],
        eltagSize: 0,
      },
    },
  ]
  const tc2 = [
    {
      headerName: '保养项目名称',
      field: 'upkeepName',
      width: 150,
    },
    {
      headerName: '状态',
      field: 'qualifiedState',
      width: 150,
      valueFormatter: (params: any) => {
        return params.value == 0 ? '不合格' : params.value == 1 ? '合格' : ''
      },
      cellStyle: (params: any) => {
        if (params.value == 0) return { color: 'red' }
        if (params.value == 1) return { color: 'green' }
      },
    },
  ]
  let configaggrid = ref({
    url: '', //接口路径
    queryData: {
      //接口参数
    },
    paginationShow: false, //分页是否显示
    invokeiIterface: false, //是否调用接
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tc2,
    fileName: 'MaintenanceForm-1',
  })

  const selectHandler = () => {
    if (idTypes.value == 1) {
      selectList()
    } else if (idTypes.value == 2) {
      selectList1()
    } else if (idTypes.value == 3) {
      selectList2()
    }
  }

  function selectList() {
    post({
      url: 'zcTemRepair/maintainDocument/findMaintainDocumentPage',
      data: {
        page: fySelet.page,
        limit: fySelet.size,
        machine: pageData.dropDownData1,
        machineCode: pageData.dropDownData,
        maintainName: pageData.dropDownData2,
      },
    }).then((res: any) => {
      gridOption3.value.setRowData(res.data.list)
      fySelet.total = res.data.total
    })
  }

  function selectList1() {
    post({
      url: 'zcTemRepair/maintainDocument/findCompleteStatePage',
      data: {
        page: fySelet.page,
        limit: fySelet.size,
        completeState: 1,
        machine: pageData.dropDownData1,
        machineCode: pageData.dropDownData,
        maintainName: pageData.dropDownData2,
      },
    }).then((res: any) => {
      gridOption.value.setRowData(res.data.list)
      fySelet.total = res.data.total
    })
  }

  function selectList2() {
    post({
      url: 'zcTemRepair/maintainDocument/findCompleteStatePage',
      data: {
        page: fySelet.page,
        limit: fySelet.size,
        completeState: 2,
        machine: pageData.dropDownData1,
        machineCode: pageData.dropDownData,
        maintainName: pageData.dropDownData2,
      },
    }).then((res: any) => {
      gridOption2.value.setRowData(res.data.list)
      fySelet.total = res.data.total
    })
  }

  const dataForm: any = reactive({
    staff: '',
    startMaintainTime: '',
  })

  const dispatchs = () => {
    if (
      gridOption3.value.getSelectedRows().length == 0 ||
      gridOption3.value.getSelectedRows().length > 1
    ) {
      return false
    }
    dataForm.staff = ''
    dataForm.startMaintainTime = ''
    post({
      url: 'admin/acl/user/findUserToken',
    }).then((res: any) => {
      if (res.code == 200) {
        if (res.data.data.departmentId == null || res.data.data.departmentId == 0) {
          Message.error('当前登陆账号无部门!')
          return
        }
        post({
          url: 'org/hrEmployee/getList',
          data: {
            deleteState: 0,
            obsoleteState: 0,
            department_id: res.data.data.departmentId,
          },
        }).then((resz: any) => {
          if (resz.code == 200) {
            wxYgList.value = resz.data
            dataForm.staff = gridOption3.value.getSelectedRows().map((res: any) => {
              return res.staff
            })
            dataForm.startMaintainTime = gridOption3.value.getSelectedRows()[0].timeType
            visible.value = true
          } else {
            Message.error(resz.message)
          }
        })
      } else {
        Message.error(res.message)
      }
    })
  }

  const visible = ref(false)

  const handleOk = async () => {
    const err = await formRef.value?.validate()
    if (!err) {
      let dataList = gridOption3.value.getSelectedRows().map((res: any) => {
        return {
          id: res.id,
          staff: dataForm.staff.toString(),
          startMaintainTime: dataForm.startMaintainTime,
        }
      })
      const res = await post({
        url: 'zcTemRepair/maintainDocument/DispatchingMaintainDocument',
        data: dataList,
      })
      if (res.code == 200) {
        Message.success(res.message)
        selectList()
        selectList1()
        return true
      } else {
        Message.error(res.message)
        return false
      }
    } else {
      return false
    }
  }

  const wxYgList: any = ref([])

  const completes = () => {
    if (gridOption3.value.getSelectedRows().length === 0) {
      return false
    }
    Modal.confirm({
      title: '系统提示',
      content: '确认完成选中的数据?',
      onOk() {
        post({
          url: 'zcTemRepair/maintainDocument/updateCompleteState',
          data: gridOption3.value.getSelectedRows().map((o: any) => {
            return o.id
          }),
        }).then(({ code, data, message }: any) => {
          if (code === 200) {
            Message.success({
              content: message,
              duration: 5000,
            })
            fySelet.page = 1
            selectList()
            selectList1()
            selectList2()
          } else {
            Message.error({
              content: message,
              duration: 5000,
            })
          }
        })
      },
    })
  }

  // const pagingList1: any = ref(pagingList)
  // const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('ProgramType01', gridOption, colState, tc)
  // const onColumnMoved = () => {
  //     saveGridState01()
  // }
  // const onColumnResized = () => {
  //     saveGridState01()
  // }
</script>
<style lang="less" scoped>
  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }

  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }
  .detail-container {
    display: flex;
    flex-wrap: wrap;
  }

  .tag-row {
    display: flex;
    justify-content: space-between;
    width: 50%; /* 确保每行占满整个容器的宽度 */
    margin-bottom: 10px; /* 设置标签行与行之间的间距 */
  }
</style>
